let order_state = 1; //查询所有订单
layui.config({
    version: '1510164124181'
}).use(['form', 'laypage', 'layer', 'element', 'laydate'], function() {
    form = layui.form;
    layer = layui.layer;
    $ = layui.jquery;
    laypage = layui.laypage; //分页
    element = layui.element; //元素操作
    laydate = layui.laydate; //时间选择器
    //日期时间范围
    laydate.render({
        elem: '#order_time',
        type: 'datetime',
        range: true
    });
    //日期时间范围
    laydate.render({
        elem: '#order_time2',
        type: 'datetime',
        range: true
    });
    $(".mystate a").click(function() {
        $(".mystate a").removeClass("red");
        $(this).addClass("red");
        order_state = $(this).attr("data-id");
        $("#order_state option[value=" + order_state + "]").attr("selected", "selected");
        SearchInfo();
    });
    inituserdata();

});

function addClickFiles() {
    $(".impFile").click();
}
function onloadInfo() {
    inituserdata();
}
function ImprotExcelUpdateSendInfo() {
    layer.open({
        type: 1,
        area: ['800px', '500px'],
        shadeClose: false, //点击遮罩关闭
        content: '<form class="am-form" style="width: 90%;margin: 0 auto;">' +
            '            <label for="username" style="font-size: 20px;">请参照下图设置excel表,再导入:</label>' +
            '            <br><br><br>' +
            '            <div class="width100"><img width="100%" src="../../img/orderShow.png"></div>' +
            '            <span class="text-danger">备注:第一行设置标题分别为订单号,快递公司,快递单号,第二行填入相应数据。<br/>则请严格按照上图导入,否则将无法批量发货</span>' +

            '            <div class="flex flex-wrap flex-col-3">' +
            '<div class="form-group-col-2">' +
            '<div class="form-label"></div>' +
            '<div class="form-cont padding_top10 margin_left2b">' +
            '<input type="button" onclick="addClickFiles()" value="好的,我知道了"  class="btn btn-info"/>&nbsp;&nbsp;' +
            // '<input type="button" value="取消" class="btn btn-danger"/>' +

            '</div>' +
            '</div>' +
            '</div>' +
            '        </form>'
    });

}

function UpdateStateInfo() {
    order_state = $("#order_state option:selected").val();
    $(".mystate a").removeClass("red");
    $(".mystate a").each(function() {
        let dataid = $(this).attr("data-id");
        if (dataid == order_state) {
            $(this).addClass("red");
        }
    });
    SearchInfo();
}


function ExpressNum() {
    var fileObj = document.getElementById("file").files[0]; // js 获取文件对象
    var form = new FormData(); // FormData 对象
    form.append("file", fileObj); // 文件对象
    $.ajax({
        url: httpurl + "/ExpressNum",
        type: "post",
        data: form,
        processData: false,
        contentType: false,
        success: function(data) {

            if (data.rtnCode == 200) {
                layer.alert(data.msg, function() {
                    inituserdata();
                    closeAllLayer()
                });
            } else {
                ExpressErrorInfo(data);
            }
        },
        error: function(err) {
            top.layer.alert("网络连接失败,稍后重试", err);
        }

    })
}

function ExpressErrorInfo(data) {
    let dataInfo = data.data;
    let infoList = "";
    for (let i = 0; i < dataInfo.length; i++) {
        infoList += '<tr>' +
            '<td>' + dataInfo[i].orderNum + '</td>' +
            '<td>' + dataInfo[i].info + '</td>' +
            '</tr>';
    }
    let contentInfo = '<div class="text-danger text-center">存在批量发货失败的订单,请核实后再试!!!</div><br/></span>' +
        '<table class="table table-bordered text-center width90 margin_auto"><thead><tr><th>订单号</th><th>失败原因</th></tr></thead><tbody>' + infoList + '</tbody></table>' +
        '<div class="flex flex-wrap flex-col-3">' +
        '<div class="form-group-col-2">' +
        '<div class="form-label"></div>' +
        '<div class="form-cont">' +
        '<input type="button" onclick="closelayer()" value="确认"  class="btn btn-info"/>&nbsp;&nbsp;' +
        '<input type="button" onclick="closelayer()" value="取消" class="btn btn-danger"/>' +
        '</div>' +
        '</div>' +
        '</div>';
    layer.open({
        type: 1,
        area: ['500px', '300px'],
        shadeClose: false, //点击遮罩关闭
        content: contentInfo
    });
}

function closelayer() {
    layer.closeAll();
}

function ClearSearchInfo() {
    $("#phone").val(""); //用户手机号
    $("#express_num").val(""); //下单号
    $("#pro_name").val(""); //宝贝名称
    $("#order_type").val(""); //订单类型
    $("#order_state").val(""); //订单状态
    $("#order_time").val(""); //下单时间
    $("#orderId").val(""); //订单号
}

function ExcelPrintOrder() {

    let phone = $("#phone").val(); //用户手机号
    let express_num = $("#express_num").val(); //下单号
    let pro_name = $("#pro_name").val(); //宝贝名称

    let order_type = $("#order_type").val(); //订单类型

    let order_time = $("#order_time").val(); //下单时间
    let startTime = "";
    let endTime = "";
    if (order_time != "") {
        startTime = order_time.split(" - ")[0];
        endTime = order_time.split(" - ")[1];
    }
    let order_time2 = $("#order_time2").val(); //支付时间
    let paystartTime = "";
    let payendTime = "";
    if (order_time2 != "") {
        paystartTime = order_time2.split(" - ")[0];
        payendTime = order_time2.split(" - ")[1];
    }
    let orderId = $("#orderId").val(); //订单号
    window.location.href = httpurl + "/derivationExport?phone=" + phone + "&express_num=" + express_num + "&order_type=" + order_type + "&pro_name=" + pro_name + "&order_state=" + order_state + "&startTime=" + startTime + "&endTime=" + endTime + "&orderId=" + orderId + "&isfree=-1" + "&paystartTime=" + paystartTime + "&payendTime=" + payendTime;
}

function inituserdata() {
    var index = top.layer.msg('加载中，请稍候', { icon: 16, time: false, shade: 0.8 });
    $("#tableInfo tbody").html("");
    let phone = $("#phone").val(); //用户手机号
    let express_num = $("#express_num").val(); //下单号
    let pro_name = $("#pro_name").val(); //宝贝名称
    let order_type = $("#order_type").val(); //订单类型
    let order_time = $("#order_time").val(); //下单时间
    let startTime = "";
    let endTime = "";
    if (order_time != "") {
        startTime = order_time.split(" - ")[0];
        endTime = order_time.split(" - ")[1];
    }
    let order_time2 = $("#order_time2").val(); //支付时间
    let paystartTime = "";
    let payendTime = "";
    if (order_time2 != "") {
        paystartTime = order_time2.split(" - ")[0];
        payendTime = order_time2.split(" - ")[1];
    }
    let orderId = $("#orderId").val(); //订单号
    if (order_state == 1) { //待发货
        $(".GetReady").show();
        $(".UpdateSendInfo").hide();
    } else if (order_state == 6) { //备货中
        $(".GetReady").hide();
        $(".UpdateSendInfo").show();
    } else {
        $(".GetReady").hide();
        $(".UpdateSendInfo").hide();
    }
    $.ajax({
        url: httpurl + "/findOrderListPc",
        cache: false,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType: 'application/json',
        data: {
            "pageNo": pageNo,
            "pageSize": pageRecords,
            "phone": phone,
            "express_num": express_num,
            "order_type": order_type,
            "pro_name": pro_name,
            "order_state": order_state,
            "startTime": startTime,
            "endTime": endTime,
            "paystartTime": paystartTime,
            "payendTime": payendTime,
            "orderId": orderId,
            "isfree": -1 //不要
        },
        success: function(data) {
            let dataHtml = "";
            if (data.rtnCode == 200) {
                let initdata = data.data.list;
                totalRecords = data.data.total;
                for (let i = 0; i < initdata.length; i++) {
                    let ClassInfo = "text-primary";
                    if (initdata[i].type == 1) {
                        ClassInfo = "text-success";
                    } else if (initdata[i].type == 2) {
                        ClassInfo = "text-warning";
                    }
                    let tempInfo = "";
                    if (initdata[i].isrefund == 1) { //有退款
                        tempInfo = '<span class="text-danger">有退款</span>&nbsp;&nbsp;&nbsp;&nbsp;';
                    }
                    dataHtml += '<tr class="shop">' +
                        '<td colspan="9" class="my-order-num">' +
                        '<span><input type="checkbox" data-id="' + initdata[i].id + '" name="box" class="aceChild"/></span>' +
                        '<a href="DetaileOrder.html?OrderId=' + initdata[i].id + '"><span>订单号：' + initdata[i].id + '</span></a>&nbsp;&nbsp;&nbsp;&nbsp;' +
                        '<span>创建时间：' + initdata[i].intime + '</span>&nbsp;&nbsp;&nbsp;&nbsp;' +
                        '<span>支付时间：' + (initdata[i].paytime == null ? "无" : initdata[i].paytime) + '</span>&nbsp;&nbsp;&nbsp;&nbsp;' + tempInfo +
                        '</td>' +
                        '</tr>';
                    let orderList = initdata[i].orderInfo;
                    let rowspanLen = orderList.length;
                    let tempCouponDefalut = (initdata[i].couponRecord == null ? "" : (initdata[i].couponRecord.couponEntity == null ? "该优惠券不存在了" : (initdata[i].couponRecord.couponEntity.name + ":" + initdata[i].couponRecord.couponEntity.val + "元")));
                    let tempCoupon = ''
                    for (let a = 0; a < orderList.length; a++) {
                        let wlinfo = "";
                        let ostate = initdata[i].state;
                        let tempinfo = "";
                        let paypoints = ""
                        if (orderList[a].fromType == 1) { //秒杀
                            tempCoupon = '' 
                        }else if(orderList[a].fromType == 17){//积分商品
                            tempCoupon = ''
                            if(initdata[i].integralWhiteGive){
                                paypoints = `<br/><span style="color:#d88795">+${orderList[a].infoPayIntegral}积分</span>`
                            }
                        }else{
                            tempCoupon = tempCouponDefalut
                            if(orderList[a].integralDeductedProportion!=0){
                                tempCoupon+=`<div>使用了${initdata[i].integralWhiteGive}积分抵扣${initdata[i].integralDeductedMoney}金额（抵扣比例${initdata[i].integralDeductedProportion}%）</div>`
                            }
                        }
                        if (ostate == 1) {
                            tempinfo = '<a href="#" onclick="UpdateOrderState(\'' + initdata[i].id + '\',6);">备货</a>&nbsp;&nbsp;&nbsp;';
                        }
                        if (ostate == 6) { //备货中
                            tempinfo = '<a href="#" onclick="UpdateOrderEntity(\'' + initdata[i].id + '\',2);">发货</a>&nbsp;&nbsp;&nbsp;';
                        }
                        if (ostate == 2 || ostate == 3) {
                            wlinfo = '<a href="#" class="text-info" onclick="SelectExpressInfo(\'' + initdata[i].express_num + '\');" >查看物流</a><br/>';
                        }
                        let ostates = (ostate == 0 ? '待付款' : (ostate == 1 ? '待发货' : (ostate == 2 ? '待收货' : (ostate == 3 ? '已收货' : (ostate == 4 ? '售后' : (ostate == 5 ? '已取消' : (ostate == 6 ? '备货' : "未知")))))));
                        dataHtml += '<tr class="item border-dashed">' +
                            '<td class="s-title">' +
                            `<div class="orderNum">${a + 1} / ${initdata[i].orderInfoNum}</div>` +
                            '<a href="#" class="J_MakePoint">' +
                            '<img src="' + visitimgurl + '/' + (orderList[a].productEntity == null ? "" : orderList[a].productEntity.headimg) + '" class="itempic"><span class="title J_MakePoint">' + (orderList[a].pname == null ? "" : orderList[a].pname) + '</span></a>' +
                            '<div class="props">' +
                            '<span>套餐: ' + (orderList[a].mname == null ? "" : orderList[a].mname) + '</span>' +
                            '<span>数量: ' + orderList[a].num + ' </span>' +
                            '</div>' +
                            '<a title="消费者保障服务，卖家承诺商品如实描述" href="#" target="_blank">' +
                            '<img src="http://img03.taobaocdn.com/tps/i3/T1bnR4XEBhXXcQVo..-14-16.png"/>' +
                            '</a>' +
                            '<div>' +
                            '<span style="color:gray;">卖家承诺72小时内发货</span>' +
                            '</div>' +
                            '</td>' +
                            // '<td>￥' + orderList[a].price + '</td>' +
                            `<td>
                                <span>￥${orderList[a].price}</span>
                                ${paypoints}
                            </td>` +
                            '<td>' + orderList[a].num + '</td>' +
                            '<td>' + tempCoupon + '</td>'
                            // `<td>
                            //     <div>${tempCoupon}</div>
                            //     <div>使用了${orderList[a].integralWhiteGive}积分抵扣￥${orderList[a].integralDeductedMoney}元</div>
                            //     <div>消耗了${orderList[a].infoPayIntegral}积分</div>
                            // </td>`
                        if (a == 0) {
                            let payPoints = ''
                            if(initdata[i].orderIntegral){
                                payPoints = `<br/><span style="font-size:12px;color:#d88795">消耗${initdata[i].orderIntegral}积分</span>`
                            }
                            // '<td class="order-rowspan" rowspan="'+rowspanLen+'">' + initdata[i].phone + '</td>' +
                            dataHtml += '<td class="order-rowspan" rowspan="' + rowspanLen + '">' + initdata[i].phone + '</td>' +
                                '<td class="order-rowspan" rowspan="' + rowspanLen + '">' +
                                '<span class="statetext">' + ostates + '</span><br/>' +
                                '<span class="text-info" onclick="updateSta(this,\'' + ostate + '\');">修改</span>' +
                                '<span class="upsta" style="display: none;">' +
                                '<select class="width65 orderstateid" style="height: 30px;" onchange="UpdateState(this,\'' + initdata[i].id + '\');">' +
                                '<option value="0">待付款</option>' +
                                '<option value="1">待发货</option>' +
                                '<option value="6">备货</option>' +
                                '<option value="2">待收货</option>' +
                                '<option value="4">售后</option>' +
                                '<option value="5">取消</option>' +
                                '</select>' +
                                '</span><br/>' +
                                '</td>' +

                                '<td class="order-rowspan" rowspan="' + rowspanLen + '">' +
                                // '<span>￥' + initdata[i].ordermoney + '</span><br/>' +
                                `<span>￥${initdata[i].ordermoney}</span>` +
                                payPoints +
                                '<br/><a  href="DetaileOrder.html?OrderId=' + initdata[i].id + '">查看详情</a><br/>' +
                                '<span>(含快递:￥' + (orderList[a].freight == null ? 0 : orderList[a].freight) + ')</span><br/>' + wlinfo +
                                '</td>' +
                                '<td class="order-rowspan" rowspan="' + rowspanLen + '">' +
                                // '<a href="DetaileOrder.html?OrderId=' + initdata[i].id + '">编辑</a>&nbsp;&nbsp;&nbsp;'+
                                tempinfo +
                                '<a href="#" onclick="UpdateOrderState(\'' + initdata[i].id + '\',5);">取消</a>&nbsp;&nbsp;&nbsp;' +
                                //'<a href="#" data-id="' + initdata[i].id + '"  data-info="deleteOrderById" onclick="DeleteInfo(this);">删除</a>' +
                                '<a href="#" data-id="' + initdata[i].id + '"  data-info="deleteOrderById" onclick="DeleteInfo(this);" style="display:' + (order_state == 101 ? "none" : "block") + '">删除</a>' +
                                '<a href="#" data-id="' + initdata[i].id + '"  data-info="updateIsdelete" onclick="updateIsdelete(this);" style="display:' + (order_state == 101 ? "block" : "none") + ' ">恢复数据</a>' +
                                '</td>' +
                                '</tr>';
                        }
                    }

                }

            } else {
                totalRecords = 0;
                dataHtml += '<tr>' +
                    '<td colspan="12" style="text-align:center;padding: 20px 0">暂无数据</td>' +
                    '</tr>';
            }
            $("#tableInfo tbody").html(dataHtml);
            top.layer.closeAll();
            page();

        },
        error: function() {
            top.layer.closeAll();
            top.layer.alert("加载失败,请检查网络设置!!")
        }

    });

}

function UpdateOrderEntity(OrderId, state) {
    layer.open({
        type: 1,
        area: ['500px', '300px'],
        shadeClose: false, //点击遮罩关闭
        content: '<form class="am-form" style="width: 80%;margin: 0 auto;">' +
            '            <br><br>' +
            '            <label for="username" style="font-size: 20px;">快递公司:</label>' +
            '            <input type="text" name="name" id="express_names" style="width: 70%;height: 30px;"/>' +
            '            <br><br><br>' +
            '            <label for="username" style="font-size: 20px;">快递单号:</label>' +
            '            <input type="text" name="username" id="express_nums" style="width: 70%;height: 30px;"/>' +
            '            <br><br><br><br>' +
            '            <div class="flex flex-wrap flex-col-3">' +

            '<div class="form-group-col-2">' +
            '<div class="form-label"></div>' +
            '<div class="form-cont">' +
            '<input type="button" onclick="SendOrderInfo(\'' + OrderId + '\')" value="确认"  class="btn btn-info"/>&nbsp;&nbsp;' +
            '<input type="button" onclick="re()" value="取消" class="btn btn-danger"/>' +

            '</div>' +
            '</div>' +
            '</div>' +
            '        </form>'
    });
}

function SendOrderInfo(OrderId) {
    let express_names = $("#express_names").val();
    let express_nums = $("#express_nums").val();
    top.layer.confirm('确认提交？', { icon: 3, title: '提示信息' }, function(index) {
        var index = top.layer.msg('提交中，请稍候', { icon: 16, time: false, shade: 0.8 });
        $.ajax({
            type: "POST",
            url: httpurl + "/SendOrderInfoExpress",
            cache: false,
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "*",
                "Access-Control-Allow-Headers": "Authorization",
                "Authorization": GetTokenInfo()
            },
            contentType: 'application/json',
            data: JSON.stringify({
                "orderid": OrderId,
                "express_name": express_names,
                "express_num": express_nums
            }),
            success: function(data) {
                layer.closeAll();
                top.layer.msg(data.msg);
                inituserdata();
            }
        });
    }, function() {

    });
}

function GetReady() { //根据选择的信息  将所有待发货状态处理成已经备货
    top.layer.confirm('确认提交？', { icon: 3, title: '提示信息' }, function(index) {
        var index = top.layer.msg('提交中，请稍候', { icon: 16, time: false, shade: 0.8 });
        $.ajax({
            url: httpurl + "/GetReady",
            cache: false,
            type:'post',
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "*",
                "Access-Control-Allow-Headers": "Authorization",
                "Authorization": GetTokenInfo()
            },
            contentType: 'application/json',
            success: function(data) {
                layer.closeAll();
                top.layer.msg(data.msg);
                inituserdata();
            },
            // error:function(res){
            //     top.layer.msg('网络请求失败，请稍后再试');
            // }
        });
    }, function() {

    });
}

function updateSta(obj) {
    $(obj).hide();
    $(obj).parent().find(".upsta").show();
}

function UpdateState(obj, id) {
    let selectid = $(obj).find("option:selected").val();
    let text = $(obj).find("option:selected").text();
    top.layer.confirm('确认提交？', { icon: 3, title: '提示信息' }, function(index) {
        var index = top.layer.msg('提交中，请稍候', { icon: 16, time: false, shade: 0.8 });
        $.ajax({
            type: "POST",
            url: httpurl + "/UpdateOrderEntityState",
            cache: false,
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "*",
                "Access-Control-Allow-Headers": "Authorization",
                "Authorization": GetTokenInfo()
            },
            contentType: 'application/json',
            data: JSON.stringify({
                "id": id,
                "state": selectid
            }),
            success: function(data) {
                layer.closeAll();
                top.layer.msg(data.msg);
                inituserdata();
            }
        });
    }, function() {

    });
}

function SelectExpressInfo(expNo) {
    $.ajax({
        url: httpurl + "/kdniaoTrack",
        cache: false,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType: 'application/json',
        data: {
            "expNo": expNo,
        },
        success: function(data) {
            // console.log(JSON.stringify(data)+"=====data");
            let status = data.showapi_res_body.status;
            let info = "";
            if (status > 1) {
                let dataInfo = data.showapi_res_body.data;

                if (dataInfo.length > 0) {
                    for (let i = 0; i < dataInfo.length; i++) {
                        info += '<li class="layui-timeline-item">' +
                            '<i class="layui-icon layui-timeline-axis">&#xe63f;</i>' +
                            '<div class="layui-timeline-content layui-text">' +
                            '<h3 class="layui-timeline-title">' + dataInfo[i].time + '</h3>' +
                            ' <p>' + dataInfo[i].context + '</p>' +
                            '</div>' +
                            '</li>';
                    }
                } else {
                    info += '暂无数据!!!';
                }

            } else {
                info = (status == -1 ? "待查询" : (status == 0 ? "查询异常" : (status == 1 ? "暂无记录" : "暂无记录")));
                //-1 待查询 0 查询异常 1 暂无记录 2 在途中 3 派送中 4 已签收 5 用户拒签 6 疑难件 7 无效单 8 超时单 9 签收失败 10 退回
            }
            layer.open({
                type: 1,
                area: ['600px', '500px'],
                shadeClose: false, //点击遮罩关闭
                content: '<ul class="layui-timeline" style="width: 50%;margin: 0 auto">' + info + '</ul>'
            });
        }
    });
}

function UpdateOrderState(OrderId, state) {

    top.layer.confirm('确认提交？', { icon: 3, title: '提示信息' }, function(index) {
        var index = top.layer.msg('提交中，请稍候', { icon: 16, time: false, shade: 0.8 });
        $.ajax({
            type: "POST",
            url: httpurl + "/UpdateOrderEntityState",
            cache: false,
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "*",
                "Access-Control-Allow-Headers": "Authorization",
                "Authorization": GetTokenInfo()
            },
            contentType: 'application/json',
            data: JSON.stringify({
                "id": OrderId,
                "state": state
            }),
            success: function(data) {
                layer.closeAll();
                top.layer.msg(data.msg);
                $(".upsta").hide();
                inituserdata();
            }
        });
    }, function() {

    });

}

function SearchInfo() {
    pageNo = 1;
    inituserdata();
}

//分页
function page() {
    laypage.render({
        elem: 'page' //注意，这里的 test1 是 ID，不用加 # 号
            ,
        count: totalRecords //数据总数，从服务端得到
            ,
        curr: pageNo //获取起始页 location.hash.replace('#!fenye=', '')
            ,
        hash: 'fenye' //自定义hash值
            ,
        layout: ['count', 'prev', 'page', 'next', 'skip'],
        limit: pageRecords,
        jump: function(obj, first) {
            //首次不执行
            if (!first) {
                pageNo = obj.curr;
                pageRecords = obj.limit; // 当前页面记录数
                inituserdata();
            }
        }
    });
}